//
//  UIImage+Resource.m
//  OMTResource
//
//  Created by 昭荣伊 on 2018/7/28.
//

#import "UIImage+Resource.h"
#import <OMTCache/OMTMemoryCache.h>

static NSString *const kImagePath = @"images";
static NSString *const kImageBundleKey = @"kImageBundleKey";
static NSString *const kImagePathSetKey = @"kImagePathSetKey";
static NSString *const kImageCachePrefixKey = @"kImageCachePrefixKey";

@implementation UIImage (Resource)

+ (instancetype)omt_imageNamed:(NSString *)name {
    NSMutableSet *imagePathSet = [OMTMemoryCache memoryValueForKey:kImagePathSetKey];
    if (!imagePathSet) {
        NSString *resourcePath = [OMTMemoryCache memoryValueForKey:OMTMemoryCacheCurrentBundlePath];
        if (!resourcePath) return nil;
        
        imagePathSet = [NSMutableSet set];
        NSString *imagePath = [resourcePath stringByAppendingPathComponent:kImagePath];
        
        BOOL isDirectory;
        [[NSFileManager defaultManager] fileExistsAtPath:imagePath isDirectory:&isDirectory];
        if (isDirectory) {
            [imagePathSet addObject:imagePath];
        }
        
        NSString *path = imagePath;
        NSArray *files = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:path error:nil];
        for (NSString *fileName in files) {
            NSString *filePath = [path stringByAppendingPathComponent:fileName];
            [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDirectory];
            if (isDirectory) {
                [imagePathSet addObject:filePath];
            }
        }
        
        if (imagePathSet) [OMTMemoryCache setMemoryValue:imagePathSet key:kImagePathSetKey];
    }
    
    NSString *imageCacheKey = [kImageCachePrefixKey stringByAppendingPathComponent:name];
    UIImage *image = [OMTMemoryCache imageForKey:imageCacheKey];
    if (image) return image;
    
    NSString *ext = [name pathExtension];
    NSString *imageName = nil;
    // 当前是 @3x 优先取 3倍图
    imageName = [NSString stringWithFormat:@"%@%@", name , ext.length > 0 ? @"" : @"@3x.png"];
    image = [self _imageWithName:imageName imageCacheKey:imageCacheKey];
    if (image) return image;
    
    // 取2倍图
    imageName = [NSString stringWithFormat:@"%@%@", name , ext.length > 0 ? @"" : @"@2x.png"];
    image = [self _imageWithName:imageName imageCacheKey:imageCacheKey];
    if (image) return image;
    
    // 取1倍图
    imageName = [NSString stringWithFormat:@"%@%@", name , ext.length > 0 ? @"" : @".png"];
    image = [self _imageWithName:imageName imageCacheKey:imageCacheKey];
    if (image) return image;
    
    return image;
}

/**
 遍历目录取图片并添加到缓存
 
 @param imageName 图片名称
 @param imageCacheKey 缓存 Kye
 @return 图片
 */
+ (UIImage *)_imageWithName:(NSString *)imageName imageCacheKey:(NSString *)imageCacheKey {
    NSMutableSet *imagePathSet = [OMTMemoryCache memoryValueForKey:kImagePathSetKey];
    UIImage *image = nil;
    for (NSString *imageDirection in imagePathSet) {
        NSString *imagePath = [imageDirection stringByAppendingPathComponent:imageName];
        if (![[NSFileManager defaultManager] fileExistsAtPath:imagePath]) continue;
        image = [UIImage imageWithContentsOfFile:imagePath];
        if (image) {
            // 异步缓存图片
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                [OMTMemoryCache storeImage:image key:imageCacheKey];
            });
            return image;
        }
    }
    return image;
}

@end
